package cl.dkns.yapal.core.db;

import cl.dkns.yapal.core.db.mapping.Category;
import cl.dkns.yapal.core.db.mapping.Product;
import cl.dkns.yapal.core.db.mapping.User;
import cl.dkns.yapal.core.db.util.SessionFactoryUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class DatabaseAccessImpl implements DatabaseAccess {


    /**
     * @param product
     */
    public void addProduct(Product product) throws DatabaseException {

        insertObject(product);
    }

    public void addCategory(Category category) throws DatabaseException{
        insertObject(category);
    }

    public void addUser(User user) throws DatabaseException{
        insertObject(user);
    }

    /**
     * @param dbObject
     */
    private static void insertObject(Object dbObject) throws DatabaseException{

        Transaction tx = null;

        Session session = SessionFactoryUtil.getInstance().getCurrentSession();

        try {

            tx = session.beginTransaction();
            session.save(dbObject);
            tx.commit();

        } catch (RuntimeException e) {

            if (tx != null && tx.isActive()) {
                try {
                    tx.rollback();
                } catch (HibernateException e1) {

                }

                throw new DatabaseException(e);
            }
        }
    }


}
